using System;
using System.Linq;
using TestCases.Utils.Comparers;

namespace TestCases.CompareAssert.Core.Selectors
{
    public class CovariantInterfacesSelector: ITypeSelector
    {
        private readonly string _interfaceName;
        public CovariantInterfacesSelector(string interfaceName)
        {
            if (interfaceName.LastIndexOf('`') < 0)
            {
                throw new ArgumentException("Interface name must be a generic type name with '`' suffix", "interfaceName");
            }
            _interfaceName = interfaceName;
        }

        public Type[] SelectFrom(Type leftType, Type rightType)
        {
            var filtered = 
                from type in leftType.GetInterfaces()
                let typeArgs = type.GetGenericArguments()
                where type.Name == _interfaceName && typeArgs.Length == 1 && typeArgs[0].IsAssignableFrom(rightType)
                select type;
                                        
            var result = filtered.OrderByDescending(x => x.GetGenericArguments()[0], TypeComparer.Instance).ToArray();                          
            return result;
        }
    }
}